import React from "react";
import { useTranslation } from "react-i18next";
import { Image, InfiniteScroll, Input, Popup, Toast } from "antd-mobile";
import Styles from "./U2U.module.less";
import { useState } from "react";
import { useNavigate } from "react-router-dom";
import InfiniteScrollContent from "@/components/InfiniteScrollContentComponent/InfiniteScrollContentComponent";
import getAssetsFile from "@/utils/pub-use";
import { useAppSelector } from "@/hooks/useAppSelector";

import {
  getApiToken,
  getTansferList,
  get_HangSalesMarket,
  get_UserTransactionOrder,
  buy_HangSalesMarketOrder,
} from "@/api/module/U2U";
import { BanlanceType } from "@/api/module/user";
const HeaderComponent = () => (
  <div className="text-center font-bold text-xl py-2">G2G</div>
);
const AssetsComponent = () => {
  const userInfo = useAppSelector((state) => state.userInfo.userInfo);
  const { t } = useTranslation();
  const navigate = useNavigate();
  const assetsList = [
    {
      image: getAssetsFile("home/third.png"),
      title: "USDT",
      key: "USDT",
    },
    // {
    //   image: getAssetsFile("home/sixth.png"),
    //   title: "RegisterBeans",
    //   key: "ZCB",
    // },
    {
      image: getAssetsFile("home/fourth.png"),
      title: "CashBeans",
      key: "XJB",
    },
  ];
  return (
    <div>
      <div className="flex items-center justify-between asstest mx-2 bg-bg-1 py-5 px-4 rounded-xl pb-6 ">
        <div className="left">
          <div className="opacity-50 text-xs">{t("bugRate")}</div>
          <div className="font-bold text-2xl mt-1">$1</div>
        </div>
        <div className="relative right flex items-center">
          <Image
            className="absolute left-0 bg-font-2 p-2 rounded-full"
            src={getAssetsFile("u2u/person-icon.png")}
            width={32}
            height={32}
            alt=""
          />
          <span className="bg-white-7 pl-10 pr-4 rounded-full text-font-2 font-semibold">
            {userInfo.level_name}
          </span>
        </div>
      </div>
      <div className="value text-white-1 py-5 px-4 bg-custom-gradient-1 rounded-xl relative -top-4 flex items-center justify-around">
        {assetsList.map((item) => {
          return (
            <div className="text-center" key={item.key}>
              <div className="flex justify-center">
                <Image src={item.image} width={32} height={32} alt="" />
              </div>
              <div className="text-xs opacity-50 mt-2">{t(item.title)}</div>
              <div className="font-bold text-xl mt-1">
                {
                  (userInfo[item.key as keyof typeof userInfo] as BanlanceType)
                    .balance
                }
              </div>
            </div>
          );
        })}
      </div>
      <div className="btn flex items-center">
        {/* <div
          onClick={() => navigate("/U2U/buy")}
          className="bg-bg-14 flex-1 rounded-lg text-center py-2"
        >
          {t("buy")}
        </div> */}
        <div
          onClick={() => navigate("/U2U/sell")}
          className="bg-bg-15 flex-1  rounded-lg text-center py-2"
        >
          {t("sell")}
        </div>
      </div>
    </div>
  );
};
const LogsComponent = () => {
  const userInfo = useAppSelector((state) => state.userInfo.userInfo);
  const navigate = useNavigate();
  const { t } = useTranslation();
  const [visible, setVisible] = useState(false);
  const [APIToken, setAPIToken] = useState("");
  const [password, setPassword] = useState<string>();
  const [buyPopupObj, setBuyPopupObj] = useState<any>({});
  const [page, setPage] = useState(1);
  const [active, setActive] = useState(0);
  const tabList = ["myCurrentTransactionLogs", "latestSalesOrder"];
  const [data, setData] = useState<
    Awaited<ReturnType<typeof getTansferList>>["data"]["list_data"]
  >([]);
  const [hasMore, setHasMore] = useState(true);

  async function loadMore() {
    const res =
      active == 0
        ? await get_UserTransactionOrder(page + "", 1)
        : await get_HangSalesMarket(page + "");

    // const append2 = await Promise.resolve(append);
    // res.data.list_data = [
    //   {
    //     transfer_id: 123456789,
    //     transfer_sn: '123456789',
    //     currency_cost: '100',
    //     currency_name: 'USDT',
    //     amount_cost: '12',
    //     add_time: '12121',
    //   },
    // ];
    setPage(page + 1);
    // @ts-ignore
    setData((val) => [...val, ...res.data.list_data]);
    setHasMore(false);
  }

  const req_buy_HangSalesMarketOrder = async (
    id: string,
    password: string,
    APIToken: string
  ) => {
    try {
      Toast.show({
        icon: "loading",
      });
      const res = await buy_HangSalesMarketOrder(id, password, APIToken);
      Toast.clear();
      setAPIToken("");
      Toast.show({ content: res.msg });
      if (res.code == 0) {
        setPassword("");
        setVisible(false);
        loadMore();
      }
      if (res.code == 1 && userInfo.paypwd_status == 0) {
        navigate("/updatePassword");
      }
    } catch (error) {
      Toast.clear();
      setAPIToken("");
    }
  };
  const reqApiToken = async (id: string) => {
    try {
      if (!password) {
        Toast.show({
          content: t("enterCompleteInformation"),
        });
        return;
      }
      if (!APIToken) {
        const res = await getApiToken();

        setAPIToken(res.data.api_token);

        req_buy_HangSalesMarketOrder(id, password, res.data.api_token);
      }
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <div>
      <div className="tab flex sticky top-0 bg-black-1 py-4">
        {tabList.map((item, index) => {
          return (
            <div
              onClick={() => {
                setPage(1);
                setData([]);
                setActive(index);
                console.log(active);
                setHasMore(true);
              }}
              key={item}
              className={`mr-4 ${active == index ? Styles["active"] : ""}`}
            >
              {t(item)}
            </div>
          );
        })}
      </div>
      <div className="logs mt-2 text-sm">
        <div className="text-black-1 border-none bg-black-1">
          {data.map((item, index) => (
            <div
              key={index}
              className="flex justify-between items-center text-white-1 bg-bg-1 mb-4 rounded-lg p-4"
            >
              {active == 0 ? (
                <div key={item.transfer_id} className="">
                  <div
                    className="id mb-1 font-bold"
                    style={{
                      fontSize: "110%",
                    }}
                  >
                    {/* {t("ID")}: {item.transfer_id} */}
                  </div>
                  <div className="type">
                    {/* {t("type")}: {item.currency_cost || item.currency_buy} */}
                    {t("type")}: {item.from_currency}
                  </div>
                  <div className="vallue-price">
                    <span>
                      {/* {t("amount")}: {item.amount_cost || item.receive_amount} */}
                      {t("amount")}: {item.num}
                    </span>
                    <span className="ml-2">
                      {/* {t("price")}: {item.cost_buy || item.buy_cost} */}
                      {t("price")}: {item.paynum}
                    </span>
                  </div>
                  <div className="date mt-1">
                    {/* {t("date")}: {item.add_time} */}
                    {t("date")}: {item.from_creat_time}
                  </div>
                </div>
              ) : (
                <div>
                  <div
                    className="type font-bold"
                    style={{
                      fontSize: "110%",
                    }}
                  >
                    {t("type")}: {item.from_currency}
                  </div>
                  {/* <div className="vallue-price">
                    <span>
                      {t('amount')}: {item.amount_cost}
                    </span>
                    <span className="ml-2">
                      {t('price')}: {item.amount_cost}
                    </span>
                  </div> */}
                  <div className="date mt-2 text-xs">
                    {t("date")}: {item.from_creat_time}
                  </div>
                </div>
              )}

              <div className="right">
                {active == 0 ? (
                  <span className="bg-bg-16 py-1 px-2 rounded-lg flex items-center">
                    {/* <span className="ml-1">进行中</span> */}
                    {item.state == "1" ? t("forSale") : t("completed")}
                  </span>
                ) : (
                  // ""
                  <div className="right-box flex flex-col items-center">
                    <span className="text-bg-16 font-bold text-lg">
                      {item.num}
                    </span>
                    <span
                      className="bg-bg-166 rounded-md text-bg-16 text-xs"
                      style={{
                        padding: "5px 20px",
                      }}
                      onClick={() => {
                        setBuyPopupObj(item);
                        setVisible(true);
                      }}
                    >
                      {t("buy")}
                    </span>
                    <Popup
                      visible={visible}
                      onMaskClick={() => {
                        setVisible(false);
                        setPassword("");
                      }}
                      onClose={() => {
                        setVisible(false);
                        setPassword("");
                      }}
                      // bodyStyle={{ height: "40vh" }}
                    >
                      <div className="bg-bg-1 text-center p-4 text-bg-3">
                        <div className="title font-bold text-sm">
                          {t("buy")}
                        </div>

                        <div className="popup-item mt-4 mb-4">
                          <div className="item-title font-bold text-left text-sm mb-3">
                            {t("purchaseQuantity")}
                          </div>
                          <Input
                            value={buyPopupObj.num}
                            readOnly
                            className="bg-black-1 text-xs p-4 rounded"
                            style={{
                              "--color": "#E99434",
                              "--font-size": "14px",
                            }}
                          />
                        </div>

                        <div className="popup-item mt-4 mb-4">
                          <div className="item-title font-bold text-left text-sm mb-3">
                            {t("usdtConsumed")}
                          </div>
                          <Input
                            value={buyPopupObj.paynum}
                            readOnly
                            className="bg-black-1 text-xs p-4 rounded"
                            style={{
                              "--color": "#E99434",
                              "--font-size": "14px",
                            }}
                          />
                        </div>

                        <div className="popup-item mt-4 mb-4">
                          <div className="item-title font-bold text-left text-sm mb-3">
                            {t("password")}
                          </div>
                          <Input
                            type="password"
                            value={password}
                            onChange={(val) => {
                              setPassword(val);
                            }}
                            className="bg-black-1 text-xs p-4 rounded"
                            style={{
                              "--color": "#E99434",
                              "--font-size": "14px",
                            }}
                            placeholder={t("enter")}
                          />
                        </div>

                        <div
                          onClick={() => reqApiToken(buyPopupObj.id)}
                          className="mt-6 bg-bg-16 py-4 rounded-md text-center text-base"
                        >
                          {t("confirm")}
                        </div>
                      </div>
                    </Popup>
                  </div>
                )}
              </div>
            </div>
          ))}
        </div>
        <InfiniteScroll loadMore={loadMore} hasMore={hasMore}>
          <InfiniteScrollContent hasMore={hasMore} />
        </InfiniteScroll>
      </div>
    </div>
  );
};
export default function U2U() {
  // i18n.changeLanguage('en');
  // const { t, i18n } = useTranslation();
  // const changeI18n = () => {
  //   i18n.changeLanguage(i18n.language == 'en' ? 'zh' : 'en');
  // };
  return (
    <div className="text-white-1 px-3 pb-28">
      <HeaderComponent />
      <AssetsComponent />
      <LogsComponent />
      {/* <span>{t('U2U')}</span>
      <button onClick={() => changeI18n()}>asd</button> */}
    </div>
  );
}
